package com.GreenWMS.DBUtil

import me.prettyprint.hector.api.*;

import java.util.Map;    
import java.util.HashMap;    


/**
 * Our application will be based on 
 * Cassandra and Hector
 * */

public class DBFactory{

    private String _databaseAddress = Configuration.getDatabaseAddress();
    private String _databasePort = Configuration.getDatabasePort();
    private String _defaultClusterName = Configuration.getDefaultClusterName();

    private Map<String, Keyspace> availableKeyspace = new HashMap<String, Keyspace>();
    public DBFactory(){
    
    }

    /**
     * Each company will have a separate key space(virtual)
     * */
    public static Keyspace getKeySpace(String company) {
        String keyspaceName = company;

        if (availableKeyspace.containsKey(company)) {
            return availabelKeyspace.get(company);
        }

        // Since the key space has not been cached yet, 
        // let's create the key space and cache

        Cluster cluster = getCluster();
        KeyspaceDefinition keyspaceDefinition = cluster.describeKeyspace(keyspace);
        if (keyspaceDefinition == null) {
            // The company doesn't have any key space yet, let's
            // create the keyspace
            KeyspaceDefinition = HFactory.createKeyspaceDefinition(keyspaceName);
        }


        // Create a key space with the same name
        Keyspace keyspace = HFactory.createVirtualKeyspace(keyspaceName,
                                                           UUID.fromString(keyspaceName), 
                                                           new StringSerializer(),
                                                           cluster);
        availabelKeyspace.put(company, keyspace);
        return keyspace;

    }

    public static Cluster getCluster() {
        return getDefaultCluster();
    }

    /**
     * Return a default cluster with name 'GreenWMS'.
     * Phase 1 we will use only one cluster across the application
     * */
    public static Cluster getDefaultCluster() {
        // Get the database configuration
        return HFactory.getOrCreateCluster(_defaultClusterName, _databaseAddress + ":" + _databasePort);
    } 
}



    
